package com.dangdang.serviceImpl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.dangdang.domain.Order;
import com.dangdang.service.OrderService;
import com.dangdang.util.HbnUtils;

/**
 * 订单管理实现类
 * 
 * @author Wangpeihu
 * @team [Never give up]
 * @since JDK1.6(建议)
 * @date 2010-1-19
 */
public class OrderServiceImpl implements OrderService {

	/**
	 * 增加订单
	 */
	@Override
	public void addOrder(Order order) {
		Session s = HbnUtils.getSession();
		try {
			s.beginTransaction();
			s.save(order);
			s.getTransaction().commit();
		} catch (Exception e) {
			s.getTransaction().rollback();
		} finally {
			s.close();
		}

	}

	/**
	 * 删除指定的订单
	 */
	@Override
	public void deleteOrderById(Integer orderId) {
		Session s = HbnUtils.getSession();
		try {
			s.beginTransaction();
			s.delete(orderId);
			s.getTransaction().commit();
		} catch (Exception e) {
			s.getTransaction().rollback();
		} finally {
			s.close();
		}

	}

	/**
	 * 获得所有的订单
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Order> findAllOrder() {
		Session s = HbnUtils.getSession();
		String hql = "from Order";
		Query query = s.createQuery(hql);
		List<Order> orderList = query.list();
		s.close();
		return orderList;
	}

	/**
	 * 根据ID获得订单<br>
	 * 如果该订单存在,将其返回.反之返回null;
	 */
	@Override
	public Order findOrderByID(Integer orderId) {
		Session s = HbnUtils.getSession();
		Order order = (Order) s.get(Order.class, orderId);
		s.close();
		if (null != order) {
			return order;
		}
		return null;
	}

	/**
	 * 更新一个订单
	 */
	@Override
	public void updateOrder(Order order) {
		Session s = HbnUtils.getSession();
		try {
			s.beginTransaction();
			s.update(order);
			s.getTransaction().commit();
		} catch (Exception e) {
			s.getTransaction().rollback();
		} finally {
			s.close();
		}
	}

}
